package com.yangxk.ureport.starter;

import com.bstek.ureport.console.UReportServlet;
import com.yangxk.ureport.provider.FileProviderListen;
import com.yangxk.ureport.provider.sql.SqlOperation;
import com.yangxk.ureport.provider.sql.SqlProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(UReportProperties.class)
@ConditionalOnWebApplication
@ConditionalOnClass(UReportServlet.class)
@ImportResource("classpath:ureport-console-context.xml")
public class UReportAutoConfiguration {

    private UReportProperties uReportProperties;

    @Autowired
    private DataSource dataSource;

    @Bean
    public ServletRegistrationBean buildUReportServlet() {
        return new ServletRegistrationBean(new UReportServlet(), "/ureport/*");
    }

    @Bean
    public FileProviderListen uReportListen() {
        FileProviderListen uReportListen = new FileProviderListen();
        uReportListen.setuReportProperties(uReportProperties);
        return uReportListen;
    }

    @Bean
    public DataSourceConfig dataSourceConfig() {
        DataSourceConfig ds = new DataSourceConfig();
        ds.setDataSource(dataSource);
        ds.setDataSourceName(uReportProperties.getDsName());
        return ds;
    }

    @Bean
    @ConditionalOnProperty(prefix = "ureport", name = "sql-provider", matchIfMissing = true)
    public SqlProvider sqlProvider() {
        SqlProvider sqlProvider = new SqlProvider();
        sqlProvider.setSqlOperation(sqlOperation());
        sqlProvider.setDisabled(!uReportProperties.isSqlProvider());
        return sqlProvider;
    }

    @Bean
    @ConditionalOnProperty(prefix = "ureport", name = "sql-provider", matchIfMissing = true)
    public SqlOperation sqlOperation() {
        SqlOperation sqlOperation = new SqlOperation();
        sqlOperation.setDataSource(dataSource);
        return sqlOperation;
    }

    public UReportAutoConfiguration(UReportProperties uReportProperties) {
        this.uReportProperties = uReportProperties;
    }
}
